package com.xyxy.platform.modules.core.utils.converter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 将对象转换为Map对象
 * Created by juju on 14-5-23.
 */
public class EntityToMapTransformer<T> implements Transformer<T, Map<String, Object>> {
    private static final Logger logger =
            LoggerFactory.getLogger(EntityToMapTransformer.class);
    Class<T> clazz;
    PropertyDescriptor[] pds;

    public EntityToMapTransformer(Class<T> clazz) {
        this.clazz = clazz;
        BeanInfo info = getBeanInfo(clazz);
        pds = info.getPropertyDescriptors();
    }

    public Map<String, Object> transform(T from) {
        return transform(from, null);
    }

    public Map<String, Object> transform(T from, Map<String, Object> defaultVal) {
        if (pds.length == 0) {
            return defaultVal;
        }
        if (null == defaultVal) {
            defaultVal = new HashMap<>(pds.length);
        }
        for (PropertyDescriptor pd : pds) {
            if ("class".equals(pd.getName()))
                continue;
            Method readMethod = pd.getReadMethod();
            if (readMethod == null) {
                continue;
            }
            try {
                defaultVal.put(pd.getName(), readMethod.invoke(from));
            } catch (Exception ex) {
                logger.error("读取属性出现异常");
            }
        }
        return defaultVal;
    }

    /**
     * 获取类反射信息
     *
     * @param clazz
     * @return
     */
    private static BeanInfo getBeanInfo(Class clazz) {
        try {
            return Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            throw new IllegalArgumentException("error: generate Table instance from Class,clazz:" + clazz, e);
        }
    }
}
